package com.itheima.service.empl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.bean.Category;
import com.itheima.bean.Dish;
import com.itheima.bean.DishFlavor;
import com.itheima.dao.DishDao;
import com.itheima.dto.DishDto;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Transactional
public class DishServiceImpl implements DishService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CategoryServiceImpl categoryService;

    @Autowired
    private DishDao dishDao;

    @Autowired
    private FlavorServiceImpl flavorService;

    /**
     * 通过category id条件查找菜品管理
     *
     * @param id
     * @return
     */
    @Override
    public List<Dish> findCond(Long id) {
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId, id);
        return dishDao.selectList(qw);
    }

    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @Override
    public int add(DishDto dishDto) {

        int row = dishDao.insert(dishDto);

        if (row > 0) {

            List<DishFlavor> flavorList = dishDto.getFlavors();

            if (flavorList != null && flavorList.size() > 0) {

                int row2 = 0;

                for (DishFlavor flavor : flavorList) {

                    flavor.setDishId(dishDto.getId());

                    row2 += flavorService.add(flavor);

                }

                return row2 == flavorList.size() ? 1 : 0;

            }
        }

        return row;

    }

    /**
     * 通过分页查询菜品
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public IPage<DishDto> findPage(int page, int pageSize, String name) {
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(name != null, Dish::getName, name);
        IPage<Dish> pag = new Page<>(page, pageSize);
        IPage<Dish> dishIPage = dishDao.selectPage(pag, qw);
        List<DishDto> list = dishIPage.getRecords().stream().map(dish -> {
            Category category = categoryService.findById(dish.getCategoryId());
            DishDto dto = new DishDto();
            dto.setCategoryName(category.getName());
            BeanUtils.copyProperties(dish, dto);
            return dto;
        }).collect(Collectors.toList());
        IPage<DishDto> dtoIPage = new Page<>();
        dtoIPage.setRecords(list);
        dtoIPage.setTotal(dishIPage.getTotal());
        return dtoIPage;
    }

    /**
     * 通过主键id查找
     *
     * @param id
     * @return
     */
    @Override
    public DishDto findById(Long id) {
        Dish dish = dishDao.selectById(id);
        DishDto dishDto = new DishDto();
        dishDto.setCategoryName(categoryService.findById(dish.getCategoryId()).getName());
        List<DishFlavor> flavorList = flavorService.findByDishId(dish.getId());
        dishDto.setFlavors(flavorList);
        BeanUtils.copyProperties(dish, dishDto);
        return dishDto;
    }

    /**
     * 修改菜单
     *
     * @param dishDto
     * @return
     */
    @Override
    public int update(DishDto dishDto) {

        int row = dishDao.updateById(dishDto);

        if (row > 0) {

            flavorService.deleteByDishId(dishDto.getId());

            List<DishFlavor> flavorList = dishDto.getFlavors();

            int row2 = 0;

            if (flavorList != null && flavorList.size() > 0) {

                for (DishFlavor flavor : flavorList) {

                    flavor.setDishId(dishDto.getId());

                    row2 += flavorService.add(flavor);

                }

                return row2 == flavorList.size() ? 1 : 0;

            }

        }

        return row;
    }

    /**
     * 通过categoryId 查询
     *
     * @param categoryId
     * @return
     */
    @Override
    public List<DishDto> list(Long categoryId, Integer status) {
        String data = (String) redisTemplate.opsForValue().get("DISH_" + categoryId);
        if (data != null) {
            TypeReference<List<DishDto>> tr=new TypeReference<List<DishDto>>(){};
            return JSON.parseObject(data,tr);
        }
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId, categoryId);
        qw.eq(status != null, Dish::getStatus, status);
        List<Dish> dishList = dishDao.selectList(qw);
        List<DishDto> dtoList = dishList.stream().map(dish -> {
            List<DishFlavor> flavorList = flavorService.findByDishId(dish.getId());
            DishDto dishDto = new DishDto();
            dishDto.setFlavors(flavorList);
            BeanUtils.copyProperties(dish, dishDto);
            return dishDto;
        }).collect(Collectors.toList());
        ValueOperations opsForValue = redisTemplate.opsForValue();
        String s = JSON.toJSONString(dishList);
        opsForValue.set("DISH_" + categoryId, s,60, TimeUnit.MINUTES);
        return dtoList;
    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @Override
    public int delete(List<Long> ids) {
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(Dish::getStatus, 1);
        qw.in(Dish::getId, ids);
        Integer row = dishDao.selectCount(qw);
        if (row > 0) {
            return -1;
        }
        int row1 = dishDao.deleteBatchIds(ids);
        for (Long id : ids) {
            flavorService.deleteByDishId(id);
        }
        return row1;
    }

    /**
     * 修改菜品成停售状态
     *
     * @param ids
     * @return
     */
    @Override
    public int updateStop(List<Long> ids) {
        List<Dish> dishes = dishDao.selectBatchIds(ids);
        int row = 0;
        for (Dish dish : dishes) {
            dish.setStatus(0);
            row += dishDao.updateById(dish);
        }
        return row == dishes.size() ? 1 : 0;
    }

    /**
     * 修改菜品成起售状态
     *
     * @param ids
     * @return
     */
    @Override
    public int updateStart(List<Long> ids) {
        List<Dish> dishes = dishDao.selectBatchIds(ids);
        int row = 0;
        for (Dish dish : dishes) {
            dish.setStatus(1);
            row += dishDao.updateById(dish);
        }
        return row == dishes.size() ? 1 : 0;
    }

}
